<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>药品管理</el-breadcrumb-item>
      <el-breadcrumb-item>药品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="3">
          <el-input placeholder="请输入药品名" v-model="queryInfo.medName" clearable
                    @clear="getMedicineList()">
          </el-input>
        </el-col>

        <el-col :span="3">
          <el-cascader
              @change="onChange"
              :options="classificationList"
              :props="{ checkStrictly: true ,label:'name'}"
              clearable></el-cascader>
        </el-col>

        <el-col :span="1">
          <el-button icon="el-icon-search" @click="handleSearch()" ></el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="medicineFormVisible=true">添加药品</el-button>
        </el-col>

      </el-row>
      <el-table :data="medicineList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="药品名" prop="medName"></el-table-column>
        <el-table-column label="规格" prop="specifications"></el-table-column>
        <el-table-column label="中西药分类" prop="classificationName"></el-table-column>
        <el-table-column label="药品分类" prop="drugWarehouseClassificationName"></el-table-column>
        <el-table-column label="厂商" prop="factory"></el-table-column>
        <el-table-column label="价格" prop="price"></el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-edit" circle size="mini" @click="editMedicineHandle(scope.row.id)"></el-button>
            <el-button type="primary" size="mini" @click="handleWareHouseManager(scope.row.id,scope.row.medName)">库存管理</el-button>
<!--            <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="removeMedicineById(scope.row.id)"></el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[4, 8, 10, 20]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next"
          :total="total">
      </el-pagination>
    </el-card>

    <!--库存模块 -->
    <el-card>
      <el-row  :gutter="20">
        <el-col :span="3">
          <div>库存管理</div>
          <div class="medName-wrapper">({{medName}})</div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="medicineWarehouseFormVisible=true">添加库存</el-button>
        </el-col>

      </el-row>
      <el-table :data="medicineWareHouseList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="药品名" prop="params.medName"></el-table-column>
        <el-table-column label="药品数量" prop="amount"></el-table-column>
        <el-table-column label="过期时间" prop="termOfValidity"></el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-edit" circle size="mini" @click="editMedicineWarehouseHandle(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="removeMedicineWareHouse(scope.row.id,scope.row.medId)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        title="添加/修改药品"
        :visible.sync="medicineFormVisible"
        width="50%"
        @close="handleMedicineFormClose">
      <el-form :model="medicine" ref="medicineFormRef" :rules="medicineRules" label-width="70px">
        <el-form-item label="药品名" prop="medName">
          <el-input v-model="medicine.medName"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="medicine.specifications"></el-input>
        </el-form-item>
        <el-form-item label="厂商" prop="factory">
          <el-input v-model="medicine.factory"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="medicine.price"></el-input>
        </el-form-item>
        <el-form-item label="药品分类" prop="content">
          <el-cascader
              @change="editFormCascaderOnChange"
              :options="classificationList"
              :props="{ checkStrictly: true ,label:'name'}"
              clearable>
          </el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleMedicineFormClose">取 消</el-button>
        <el-button type="primary" @click="submitMedicineForm()">确 定</el-button>
      </span>
    </el-dialog>

    <!--添加库存表单模块-->
    <el-dialog
        title="添加/修改库存"
        :visible.sync="medicineWarehouseFormVisible"
        width="50%"
        @close="handleMedicineWarehouseFormClose">
      <el-form :model="stock" :rules="stockRules" ref="stockFormRef" label-width="70px">
        <div class="demo-input-suffix">
          药品名称：{{medName}}
        </div>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="stock.amount"></el-input>
        </el-form-item>
        <el-form-item label="保质期" prop="termOfValidity">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="stock.termOfValidity"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleMedicineWarehouseFormClose">取 消</el-button>
        <el-button type="primary" @click="submitMedicineWarehouseForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import dictApi from "@/api/dict";
import medicineApi from "@/api/medicine";
import medicineAmountApi from "@/api/medicine-amount";
export default {
  name: "Medicine",
  data(){
    return{
      // 获取用户列表参数对象
      page:1,
      limit:4,
      total:0,
      medName:'',
      medicineFormVisible:false,
      medicineWarehouseFormVisible:false,
      queryInfo:{},
      medicine:{},
      stock:{
        params:{medName:''}
      },
      stockRules:{

      },
      medicineRules:{
        medName:[
          {required: true, message: "药品名不能为空", trigger: 'blur'},
        ],
        specifications:[
          {required: true, message: "规格不能为空", trigger: 'blur'},
        ],
        factory:[
          {required: true, message: "厂商不能为空", trigger: 'blur'},
        ],
        classificationCode:[
          {required: true, message: "药品分类不能为空", trigger: 'blur'}
        ],
        price:[{required: true, message: "价格不能为空", trigger: 'blur'}
        ]
      },
      classificationList:[],
      medicineList:[],
      medicineWareHouseList:[],
    }
  },
  created() {
    this.getMedicineClassification()
    this.getMedicineList()
  },
  methods:{
    //添加库存
    async submitMedicineWarehouseForm(){
      this.$refs["stockFormRef"].validate(async valid => {
        if (valid) {
          if (this.stock.medId==null){
            return this.$message.error('请先选中对应的药品进行库存管理')
          }
          if (this.stock.id){
            const {data: res} = await medicineAmountApi.update(this.stock)
            if (res.code === 200) {
              this.$message.success('更新成功')
            } else {
              return this.$message.error('更新失败')
            }
          }else{
            //添加
            const {data: res} = await medicineAmountApi.add(this.stock)
            if (res.code !== 200) {
              this.$message.error('添加失败')
            } else {
              this.$message.success('添加成功')
            }
          }
          await this.handleWareHouseManager(this.stock.medId, this.medName)
          this.handleMedicineWarehouseFormClose()
        } else {
          return this.$message.error('添加失败，请检查参数格式')
        }
      })
    },
    //显示库存
    async handleWareHouseManager(medId,medName){
      const{data:res} = await medicineAmountApi.find(medId)
      if(res.code!==200){
        return this.$message.error('获取药品分类列表失败')
      }
      this.medName = medName
      this.stock.medId = medId
      this.medicineWareHouseList = res.data
    },
    //监听药品分类选择器
    editFormCascaderOnChange(val){
      if (val.length===0){
        this.medicine.drugWarehouseClassificationId = null
        this.medicine.classificationCode = null
      }
      if (val[1]!=null){
        this.medicine.drugWarehouseClassificationId = val[0]
        this.medicine.classificationCode = val[1]
      }
    },
    onChange(val){
      if (val[0]!=null){
        this.queryInfo.drugWarehouseClassificationId = val[0]
        if (val[1]==null){
          this.queryInfo.classificationCode=null
        }
      }else{
        this.queryInfo.drugWarehouseClassificationId=null
        this.queryInfo.classificationCode=null
      }
      if (val[1]!=null){
        this.queryInfo.classificationCode = val[1]
      }
    },
    async getMedicineClassification(){
      const{data:res} = await dictApi.findChildData(139)
      if(res.code===200){
        this.classificationList = res.data
      }else{
        return this.$message.error('获取药品分类列表失败')
      }
    },
    handleSearch(){
      this.page = 1
      this.getMedicineList()
    },
    async getMedicineList(){
      this.medicineList=[]
      const{data:res} = await medicineApi.find(this.page,this.limit,this.queryInfo)
      if(res.code===200){
        this.medicineList = res.data.records
        this.total = res.data.total
        this.page = res.data.current
      }else{
        return this.$message.error('获取药品列表失败')
      }
    },
    handleSizeChange(newSize){
      this.limit =newSize
      this.getMedicineList()
    },
    handleCurrentChange(newPage){
      this.page=newPage
      this.getMedicineList()
    },
    // //删除药品
    // async removeMedicineById(id){
    //   const confirmResult =await this.$confirm('此操作将删除该药品, 是否继续?', '提示',
    //       {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'warning'
    //       }).catch(err=>err)
    //   if(confirmResult!='confirm'){
    //     return this.$message.info('已取消删除')
    //   }
    //
    //   // axios delete请求删除id
    //   const {data:res}= await this.$http.delete(`/notice/deleteById/${id}`)
    //
    //   if(res.code!==200){
    //     return this.$message.error('删除失败')
    //   }
    //   this.$message.success('确认删除')
    //   // 刷新药品列表
    //   await this.getMedicineList()
    // },
    //提交药品表单
    async submitMedicineForm(){
      //参数校验
      this.$refs["medicineFormRef"].validate(async valid => {
        if (valid) {
          if (this.medicine.drugWarehouseClassificationId == null || this.medicine.classificationCode == null) {
            return this.$message.error('请添加药品分类')
          }
          if (this.medicine.id){
            const {data: res} = await medicineApi.update(this.medicine)
            if (res.code === 200) {
              this.$message.success('更新成功')
              this.handleMedicineFormClose()
            } else {
              return this.$message.error('更新失败')
            }
          }else{
            //添加
            const {data: res} = await medicineApi.add(this.medicine)
            if (res.code === 200) {
              this.$message.success('添加成功')
              this.handleMedicineFormClose()
            } else {
              return this.$message.error('添加失败')
            }
          }
          await this.getMedicineList()
        } else {
          return this.$message.error('添加失败，请检查参数格式')
        }
      })
    },
    //提交库存表单

    //删除库存
    async removeMedicineWareHouse(id,medId){
        const confirmResult =await this.$confirm('此操作将删除该库存, 是否继续?', '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).catch(err=>err)
        if(confirmResult!='confirm'){
          return this.$message.info('已取消删除')
        }
      const{data:res} = await medicineAmountApi.delete(id)
      if (res.code===200){
        this.$message.success('删除成功')
        await this.handleWareHouseManager(medId)
      }else{
        return this.$message.error('删除失败')
      }
    },
    async editMedicineHandle(id){
      const{data:res} = await medicineApi.info(id);
      this.medicine = res.data
      this.medicineFormVisible = true
    },
    async editMedicineWarehouseHandle(id){
      const{data:res} = await medicineAmountApi.info(id);
      this.stock = res.data
      this.medicineWarehouseFormVisible = true
    },
    handleMedicineFormClose(){
      this.medicineFormVisible = false
      this.$refs['medicineFormRef'].resetFields();
      this.medicine={}
    },
    handleMedicineWarehouseFormClose(){
      this.medicineWarehouseFormVisible = false
      this.$refs['stockFormRef'].resetFields();
      this.stock = {params:{medName:''}}
    }

  },
}
</script>

<style lang="less" scoped>
.demo-input-suffix{
  margin-bottom: 20px;
}
.medName-wrapper{
  margin-top: 20px;
}
</style>